<template>
  <el-upload
    :disabled="disabled"
    class="back-picture"
    :class="{ custumWH: custumWH }"
    name="uploadFile"
    multiple
    list-type="picture-card"
    v-model:file-list="defaultFileList"
    :accept="acceptImageTypes"
    :on-change="changeFile"
    :on-remove="handleRemove"
    :before-upload="beforeAvatarUpload"
    :on-preview="handlePreview"
    :auto-upload="false"
  >
    <el-icon class="el-icon-plus" :size="56">
      <span>上传</span>
    </el-icon>
  </el-upload>
  <el-progress v-if="processLoadding" :percentage="loadProgress" />
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import { importFileForEcm, previewEcmImage } from "../../utils/ecm";
import NotifMessage from "/@/utils/message/notification";
import { acceptImageTypes } from "/@/utils/file";

export default defineComponent({
  name: "ecmImage",
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    custumWH: {
      type: Boolean,
      default: false
    },
    files: {
      type: Array,
      default: () => []
    }
  },
  emits: ["setFile"],
  setup(props, { emit }) {
    let index = 0;
    let fileArr = [];
    let docId = import.meta.env.VITE_APP_ECM_DOCID;
    const accpet = "image/*";
    const processLoadding = ref(false);
    const loadProgress = ref(0);
    const uploadRef = ref(null);
    const defaultFileList = ref<any>([]);
    const changeFile = async file => {
      try {
        processLoadding.value = true;
        loadProgress.value = 10;
        const res: any = await importFileForEcm(docId, file.raw);
        let fileObj = {
          name: file.name,
          fileName: file.name,
          uuidFile: res.docid,
          fileSize: file.size,
          fileType: "image",
          url: URL.createObjectURL(file.raw!)
        };
        fileArr.push(fileObj);

        loadProgress.value = 100;
        let timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
          processLoadding.value = false;
          emit("setFile", fileArr);
        }, 500);
      } catch (e) {
        NotifMessage.error(e?.message);
      }
      // emit("setFile", {
      //   file: defaultFileList.value,
      //   // fileStr: JSON.stringify(defaultFileList.value)
      // });
    };

    // const handlePreview = (item: any) => {

    //   // if (item.response) {
    //   //   window.open(
    //   //     `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
    //   //   );
    //   // } else {
    //   //   window.open(
    //   //     `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
    //   //   );
    //   // }
    // };

    const handlePreview = (item: any) => {
      if (item.response) {
        // let el=item.response.data
        window.open(
          `${location.origin}${location.pathname}#/preview?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
        );
      } else {
        if (item.name) {
          let el = fileArr.find(a => a.name == item.name);
          window.open(
            `${location.origin}${location.pathname}#/preview?uuidFile=${el.uuidFile}&fileName=${el.fileName}`
          );
        } else if (item.fileName) {
          let el = fileArr.find(a => a.fileName == item.fileName);
          window.open(
            `${location.origin}${location.pathname}#/preview?uuidFile=${el.uuidFile}&fileName=${el.fileName}`
          );
        }
      }
    };

    const beforeAvatarUpload = rawFile => {
      if (rawFile.type !== "image/png") {
        NotifMessage.error("Avatar picture must be JPG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        NotifMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    };

    const handleRemove = file => {
      fileArr = fileArr.filter(item => {
        return item.name !== file.name;
      });
      emit("setFile", fileArr);
    };
    const getImageUrl = async file => {
      const res = await previewEcmImage(file.uuidFile, 80, 80);
      file["url"] = window.URL.createObjectURL(res);
    };

    watch(
      () => props.files,
      async (val, oldVal) => {
        if (val.length > 0 && index === 0) {
          index++;
          let arr = [];
          for (let i = 0; i < val.length; i++) {
            let el: any = val[i];
            if (el.response) {
              await getImageUrl(el.response.data);
              arr.push(el.response.data);
            } else {
              await getImageUrl(el);
              arr.push(el);
            }
          }
          if (oldVal == null || oldVal.length === 0) {
            fileArr = JSON.parse(JSON.stringify(arr));
            defaultFileList.value = arr;
          }
        }
      },
      {
        immediate: true
      }
    );

    return {
      processLoadding,
      loadProgress,
      accpet,
      uploadRef,
      changeFile,
      defaultFileList,
      beforeAvatarUpload,
      acceptImageTypes,
      handleRemove,
      handlePreview
    };
  }
});
</script>
<style>
.avatar {
  width: 100px;
  height: 100px;
}

.ecm-upload .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #f89c34;
}

.back-picture {
  .el-upload-list__item {
    width: 56px;
    height: 56px;

    .el-upload-list__item-actions {
      font-size: 18px;
    }
  }

  .el-upload--picture-card {
    width: 56px;
    height: 56px;
    background: #fdfdff;
    border-radius: 4px;
    border: 1px solid #e4e8f2;

    i {
      height: 100%;
      width: 100%;
      line-height: 100%;
      font-size: 18px;
      color: #8c939d;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #8895b7;
      }
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
